package com.netafull.twitter;

import com.netafull.R;
import com.netafull.util.CloseUtil;

import twitter4j.TwitterException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class TwitterLoginBrowser extends Activity{
	private String auth_url = "";
	TwitterConnect tc;
	ProgressDialog progressDialog;
	ProgressDialog progressDialog2 = null;
	WebView webView;
	String oauthToken = "";
    String oauthVerifier = "";
    String tokenurl = "";
    ConnectTask task;
    ProcessHandle phand;
    Bitmap userimg;
    boolean b = false;
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);  
	    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
	    requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.twitter_login);
        
        CloseUtil.activityList.add(TwitterLoginBrowser.this);
        
        task = new ConnectTask(TwitterLoginBrowser.this);  
		task.execute("getloing");
		phand = new ProcessHandle();
        webView = (WebView)findViewById(R.id.webview);
        progressDialog = new ProgressDialog(TwitterLoginBrowser.this);
        progressDialog.setTitle("Please wait...");
        progressDialog.setMessage("Please wait...");
        progressDialog.setIndeterminate(true);
        progressDialog.show();
        
        //twitter 页面
        webView.requestFocus(View.FOCUS_DOWN);
        webView.setWebViewClient(new WebViewClient(){

            public void onPageStarted(WebView view, String url, Bitmap favicon){
            }
           
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.e("caget", "onPageFinished url = " + url);
                if(url != null && url.startsWith(CONST.CALLBACK_URL)){
                	
                	
                    String[] urlParameters = url.split("\\?")[1].split("&");
                   

                    if(urlParameters[0].startsWith("oauth_token")){
                        oauthToken = urlParameters[0].split("=")[1];
                    }else if(urlParameters[1].startsWith("oauth_token")){
                        oauthToken = urlParameters[1].split("=")[1];
                    }

                    if(urlParameters[0].startsWith("oauth_verifier")){
                        oauthVerifier = urlParameters[0].split("=")[1];
                    }else if(urlParameters[1].startsWith("oauth_verifier")){
                        oauthVerifier = urlParameters[1].split("=")[1];
                    }
                    tokenurl = url;
                    try {
                    	TwitterConnect.accessToken = TwitterConnect.twitter.getOAuthAccessToken(TwitterConnect.requestToken,oauthVerifier);
                    	
                    	
                    	WebTask wt = new WebTask();
                    	wt.execute("");
					} catch (TwitterException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
                }else{
                	if(progressDialog2 != null){
                    	progressDialog2.dismiss();
                    }
                }
                
            }
        });
        webView.setWebChromeClient(new WebChromeClient(){
			//页面加载过程中
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
				if(newProgress == 100){
					if(progressDialog2 != null){
	                	progressDialog2.dismiss();
	                }
				}
				if(newProgress == 1){
					new Thread(){
	                	public void run(){
	                		Message msg = phand.obtainMessage();
	            			phand.sendMessage(msg);
	                	}
	                	
	                }.start();
				}
				
			}
			public void onReceivedTitle(WebView view, String title) {
				
				super.onReceivedTitle(view, title);
				
			}
		});
        
    }
    /**
     * 获取用户头像跟 用户名 任务
     * @author Administrator
     *
     */
    public class WebTask extends AsyncTask<String, Integer, String>{
    	@Override
		protected String doInBackground(String... params) {
    		String re = null;
    		if(oauthToken != "" && oauthVerifier != ""){
    			String userimgurl = "";
				try {
					userimgurl = TwitterConnect.twitter.showUser(TwitterConnect.accessToken.getUserId()).getProfileImageURL().toString();
				} catch (TwitterException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
    			String username = tc.getUserName();
    			if(userimg != null) userimg.recycle();
            	userimg = tc.getUserImg(userimgurl);
            	//登陆成功 回到来的画面
				Intent it = new Intent();
				Bundle rbd = new Bundle();
				System.out.println("ready back");
				rbd.putParcelable("userimg", userimg);
				rbd.putString("username", username);
				it.putExtras(rbd);
            	//保存登陆状态
            	SharedPreferences pref=getSharedPreferences(
                        CONST.PREFERENCE_NAME,
                        MODE_PRIVATE);

                SharedPreferences.Editor editor=pref.edit();
                editor.putString("oauth_token",TwitterConnect.accessToken.getToken());
                editor.putString("oauth_token_secret",TwitterConnect.accessToken.getTokenSecret());
                editor.putString("status","available");
                editor.putString("username",username);
                editor.putString("userimgurl",userimgurl);
                editor.putString("tokenurl",tokenurl);
                editor.putString("buttonstate", "true");

                editor.commit();
                
                TwitterLoginBrowser.this.setResult(1, it);
				re = "ok";
                rbd.clear();
			}
			return re;
		}
		protected void onCancelled() {  
			super.onCancelled();
			
			progressDialog2.dismiss();
		}
		protected void onPostExecute(String result) {  
			if(progressDialog2 != null){
            	progressDialog2.dismiss();
            }
			if(result.equals("ok")){
				Toast.makeText(TwitterLoginBrowser.this, "Login Successful", Toast.LENGTH_LONG).show();
			}else{
				Toast.makeText(TwitterLoginBrowser.this, "Get user info failure", Toast.LENGTH_LONG).show();
			}
			TwitterLoginBrowser.this.finish();
			
		}  
		@Override  
		protected void onPreExecute() {  
			
		}
		protected void onProgressUpdate(Integer... values) {  
			
		}  
    }
    /**
     * 获取认证任务
     * @author Administrator
     *
     */
    public class ConnectTask extends AsyncTask<String, Integer, String> {
		
		
		public ConnectTask(Context con){
			
		}
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			tc = new TwitterConnect(TwitterLoginBrowser.this);
	        try {
				auth_url = tc.twitterLoginOauth();
			} catch (TwitterException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
			return auth_url;
		}
		protected void onCancelled() {  
			super.onCancelled();
			
			progressDialog.dismiss();
		}
		protected void onPostExecute(String result) {
			if(progressDialog.isShowing()){
				progressDialog.dismiss();
			}
			if(auth_url != ""){
				webView.loadUrl(auth_url);
			}
			else{
				Toast.makeText(TwitterLoginBrowser.this, "Authentication failure", Toast.LENGTH_LONG).show();
				
				TwitterLoginBrowser.this.finish();
			}
			
			
		}  
		@Override  
		protected void onPreExecute() {  
			// 任务启动，可以在这里显示一个对话框，这里简单处理  
			
			System.out.println("task being");
		}
		protected void onProgressUpdate(Integer... values) {  
			// 更新进度  
			System.out.println(""+values[0]);
		}  
	}
    public boolean onKeyDown(int keyCode, KeyEvent event){
    	//按back键的时候，如果info页面打开 就执行关闭弹出窗口的操作，否则退出	  
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(progressDialog.isShowing()){
				progressDialog.dismiss();
				return true;
			}
		}
    	return super.onKeyDown(keyCode, event);
    }

    public void onDestroy(){
        super.onDestroy();
        if(userimg != null) userimg.recycle();
    }
	/**
	 * 转轮 handle
	 */
	class ProcessHandle extends Handler{
		public void handleMessage (Message msg) {
			progressDialog2 = new ProgressDialog(TwitterLoginBrowser.this);
		    progressDialog2.setTitle("Please wait...");
		    progressDialog2.setMessage("Please wait...");
		    progressDialog2.setIndeterminate(true);
			progressDialog2.show();

		}
	}
	@Override
	protected void onUserLeaveHint() {
		// TODO Auto-generated method stub
		super.onUserLeaveHint();
		if(!b){
			System.out.println("开始销毁Activity");
			CloseUtil.closeActivity();
		}else{
			System.out.println("没有销毁Activity");
		}
	}
}
